package org.holynite.fieldmanage.managed.controller

import org.holynite.fieldmanage.ejbs.AuthorizationManagement
import org.holynite.fieldmanage.entities.AdministratorRole
import org.holynite.fieldmanage.entities.RolePrivilege
import org.holynite.fieldmanage.managed.model.RoleManageFormBean
import org.holynite.fieldmanage.managed.support.RolesBean
import org.holynite.fieldmanage.types.Privileges
import org.holynite.fieldmanage.utils.LocaleString

import javax.ejb.EJB
import javax.faces.bean.ManagedBean
import javax.faces.bean.ManagedProperty
import javax.faces.bean.ViewScoped
import javax.inject.Inject

/**
 * Created by midnite on 15/1/12.
 */
@ManagedBean
@ViewScoped
class AdminRoleBean implements Serializable {

	def selectedRole

	@EJB(beanName = "adminRoleControl")
	AuthorizationManagement roleService
    @ManagedProperty("#{roleManageFormBean}")
    RoleManageFormBean rmForm
    @ManagedProperty("#{rolesBean}")
    RolesBean rolesBean
	@Inject
	LocaleString locale

	AdminRoleBean() {

	}

	def saveRole() {
		if (rmForm.addMode) {
			def newRolePrivileges = rmForm.selectedPrivileges.collect { p ->
               new RolePrivilege(privilege: Privileges.findByCodeSign(p))
            }
			AdministratorRole newRole = new AdministratorRole(role: rmForm.roleName, privileges: newRolePrivileges)
			roleService.addRole(newRole)
		} else {
			def role = rolesBean.roles.find { it.svrid.equals(selectedRole) }
			role.role = rmForm.roleName
			role.privileges = rmForm.selectedPrivileges.collect { v ->
                new RolePrivilege(privilege: Privileges.findByCodeSign(v))
            }
			roleService.saveRole(role)
		}
		rolesBean.initiate()
        rmForm.clearForm()
		null
	}

	def deleteRole() {
		if (rmForm.addMode) throw new Exception(locale.fetch("warningDeleteInNew"))
		roleService.removeRole(selectedRole)
        rolesBean.initiate()
        rmForm.clearForm()
		null
	}
}
